const StringBase = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
const StringBaseLength = StringBase.length;

function randomStr(length = 10) {
  let str = "";
  for (let i = 0; i < length; i++) {
    const index = Math.floor(Math.random() * StringBaseLength);
    str += StringBase.charAt(index);
  }
  return str;
}

/**
 * 字符串工具类
 */
const Strings = {
  isEmpty: (o: string | null | undefined) => o === null || o === undefined || o === "",
  isNotEmpty: (o: string | null | undefined): o is string => !Strings.isEmpty(o),
  isBlank: (o: string | null | undefined) => Strings.isEmpty(o) || o?.trim() === "",
  isNotBlank: (o: string | null | undefined): o is string => !Strings.isBlank(o),

  randomStr,
};

export default Strings;

const cacheStringFunction = (fn: (str: string) => string) => {
  const cache = Object.create(null);
  return (str: string) => {
    const hit = cache[str];
    return hit || (cache[str] = fn(str));
  };
};
const camelizeRE = /-(\w)/g;

export const camelize = cacheStringFunction(str => {
  return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ""));
});
